package cfdt.common.controller;

import java.lang.reflect.Method;

import cfdt.common.enums.CommonCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cfdt.common.utils.BeanUtils;
import cfdt.common.vo.ObjectBaseResponse;
import cfdt.tools.util.StringUtils;

@RestController
public class ReceiveTaskController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @SuppressWarnings("rawtypes")
    @GetMapping("runTask")
    public ObjectBaseResponse runTask(String beanName, String methodName, String params){
        ObjectBaseResponse response = new ObjectBaseResponse<>();
        logger.info("定时任务开始执行 - bean：{}，方法：{}，参数：{}", beanName, methodName, params);
        long startTime = System.currentTimeMillis();

        try {
            Object target = BeanUtils.getBean(beanName);

            Method method = null;
            if (StringUtils.isNotEmpty(params)) {
                method = target.getClass().getDeclaredMethod(methodName, String.class);
            } else {
                method = target.getClass().getDeclaredMethod(methodName);
            }

            ReflectionUtils.makeAccessible(method);
            Object methodResult = null;
            if (StringUtils.isNotEmpty(params)) {
                methodResult = method.invoke(target, params);
            } else {
                methodResult = method.invoke(target);
            }
            if(methodResult instanceof ObjectBaseResponse) {
                response = (ObjectBaseResponse) methodResult;
            }
        } catch (Exception e) {
            logger.error(String.format("定时任务执行异常 - bean：%s，方法：%s，参数：%s ", beanName, methodName, params), e);
            response = ObjectBaseResponse.error(CommonCodeEnum.CODE_9999, e.getMessage());
        }

        long times = System.currentTimeMillis() - startTime;
        logger.info("定时任务执行结束 - bean：{}，方法：{}，参数：{}，耗时：{} 毫秒", beanName, methodName, params, times);
        return response;
    }

}
